package chinaums2

import (
    "fmt"
	"errors"
	"github.com/astaxie/beego"
)

type RefundQueryReq struct {
	TranType        string  `form:"TranType"`
	JavaCharset     string  `form:"JavaCharset"`
	Version         string  `form:"Version"`
	UserId          string  `form:"UserId"`
	Pwd             string  `form:"Pwd"`
	MerId           string  `form:"MerId"`
	ShoppingDate    string  `form:"ShoppingDate"`
	OrderNo         string  `form:"OrderNo"`
	RefundNo        string  `form:"RefundNo,omitempty"`
	ComeFrom        string  `form:"ComeFrom,omitempty"`
	RefundStartDate string  `form:"RefundStartDate,omitempty"`
	RefundEndDate   string  `form:"RefundEndDate,omitempty"`
}

type RefundQueryRsp struct {
    Code             string  `form:"Code"`
	Message          string  `form:"Message"`
	MerId+RefundNo   string  `form:"MerId+RefundNo"`
	OrderNo          string  `form:"OrderNo"`
	ShoppingDate     string  `form:"ShoppingDate"`
	SubmitRefundDate string  `form:"SubmitRefundDate"`
	PayAmount        string  `form:"PayAmount,omitempty"`
	RefundAmount     string  `form:"RefundAmount,omitempty"`
	RefundResult     string  `form:"RefundResult,omitempty"`
	ComeFrom         string  `form:"ComeFrom,omitempty"`
}

func MicroAppPay(account,terminal,noticeUrl,orderId,currency,amount,openId,firstName,lastName,ipAddr,productName ,key string)(payInfo string, err error){
	req := new(PayReq)
	req.Account = account
	req.Terminal = terminal
	req.NoticeUrl = noticeUrl
	req.Methods = "WX"
	req.OrderNumber = orderId
	req.OrderCurrency = currency
	req.OrderAmount = amount
	req.CustomerId = openId
	req.BillingFirstName = firstName
	req.BillingLastName = lastName
	req.BillingEmail = openId + "@dhfapp.com"
	req.BillingCountry = "CN"
	req.BillingIp = ipAddr
	req.ProductName = productName
	req.BackUrl = "N/A"
	req.SignValue = makeOrderSign(req, key)
	reqURL := "https://secure.oceanpayment.com/gateway/directservice/pay"
	sdk := NewSDK(reqURL)
	rsp := new(PayRsp)
	_, err = sdk.Request(req, rsp)
	if err != nil {
		beego.Debug("OceanPayment MicroAppPay err:", err.Error())
		return
	}
	if rsp.PaymentStatus == "0" {
	   err = errors.New(rsp.PaymentDetails)
	}
	payInfo = rsp.PaymentBankInfo
	return
}

func makeOrderSign(payReq *PayReq, key string) string {
	str := payReq.Account
	str += payReq.Terminal
	str += payReq.OrderNumber
	str += payReq.OrderCurrency
	str += payReq.OrderAmount
	str += payReq.BillingFirstName
	str += payReq.BillingLastName
	str += payReq.BillingEmail
	str += key
	return fmt.Sprintf("%x", sHA256([]byte(str)))
}
